<?php
declare (strict_types=1);

namespace app\common\library\wechat;

use app\common\library\helper;

/**
 * 订阅消息
 * Class Message
 * @package app\common\library\wechat
 */
class Message extends WxBase
{
    /**
     * 发送订阅消息
     * API文档地址：https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/mp-message-management/subscribe-message/sendMessage.html
     * @param string $template_id 模板ID
     * @param string|null $page 页面地址
     * @param string $touser 接收者（用户）的 openid
     * @param array $data 模板内容
     * @return mixed
     * @throws BaseException
     */
    public function sendMessage(string $template_id, string $page = null, string $touser = '', array $data = [])
    {
        // 微信接口url
        $accessToken = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={$accessToken}";
        // 构建请求
        $data = compact('template_id', 'touser', 'data');
        $data['lang'] = 'zh_CN';
        // $data['miniprogram_state'] = 'trial';
        $data['miniprogram_state'] = 'formal';
        !is_null($page) && $data['page'] = $page;
        // 返回结果
        $result = $this->post($url, helper::jsonEncode($data));
        return helper::jsonDecode($result);
    }
}